package com.yuzhyn.hiops.app.utils;

import com.yuzhyn.azylee.core.datas.exceptions.ExceptionTool;
import com.yuzhyn.azylee.core.logs.Alog;
import com.yuzhyn.azylee.core.systems.commons.SystemTypeTool;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Linux 系统执行 Shell 工具（注意执行权限）
 */
public class LinuxShellTool {

    public static List<String> execute(String path, String cmd) {
        try {
            File dir = new File(path);
            String s = null;
            Process p = Runtime
                    .getRuntime()
                    .exec(
                            new String[]{"/bin/sh",
                                    "-c",
                                    cmd}, null, dir);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // 标准输出命令
            while ((s = stdInput.readLine()) != null) {
                Alog.i("i   " + s);
            }
            // 标准错误的输出命令
            while ((s = stdError.readLine()) != null) {
                Alog.e("e   " + s);
            }
        } catch (Exception ex) {
            Alog.i(ExceptionTool.getStackTrace(ex));
        }
        return null;
    }

    public static List<String> sh(String cmd) {
        List<String> result = null;
        if (!SystemTypeTool.isLinux()) {
            Alog.w("暂不支持非Linux的系统");
            return result;
        }
        try {
            String[] cmdA = {"/bin/sh", "-c", cmd};
            Process process = Runtime.getRuntime().exec(cmdA);
            LineNumberReader br = new LineNumberReader(new InputStreamReader(process.getInputStream()));
            result = new ArrayList<>();
            String line;
            while ((line = br.readLine()) != null) {
                result.add(line);
                Alog.v("v   " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void executeNewFlow() {
        Runtime run = Runtime.getRuntime();
        File wd = new File("/bin");
        System.out.println(wd);
        Process proc = null;
        try {
            proc = run.exec("/bin/bash", null, wd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (proc != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            out.println("cd /home/test");
            out.println("pwd");
            out.println("rm -fr /home/proxy.log");
            out.println("exit");//这个命令必须执行，否则in流不结束。
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                proc.waitFor();
                in.close();
                out.close();
                proc.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<String>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            // out.println("cd /home/test");
            // out.println("pwd");
            // out.println("rm -fr /home/proxy.log");
            out.println("exit");// 这个命令必须执行，否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                System.out.println(rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return rspList;
    }

    public static void main(String[] args) {
        Alog.e("--------------------------------------");
        execute("/home", "java -version");
        Alog.e("--------------------------------------");
        sh("java -version");
        Alog.e("--------------------------------------");

//        execute("/home/yuzhyn/temp", "nohup java -jar bigbird-app-0.0.1-SNAPSHOT.jar &");
//
//        Alog.e("--------------------------------------");
//        Alog.e("--------------------------------------");
//
//        List<String> rs = sh("java -version");
//        Alog.i(rs);
//
//        Alog.e("--------------------------------------");
//
//        List<String> rs2 = LinuxShellTool.executeNewFlow(Arrays.asList("ls", "java -version"));
//        Alog.i(rs2);
    }
}
